package com.itany.nmms.controller;

import com.itany.mvc.annotation.RequestMapping;
import com.itany.nmms.entity.Staff;
import com.itany.nmms.exception.CodeErrorException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.exception.StaffNotExistException;
import com.itany.nmms.factory.ObjectFactory;
import com.itany.nmms.service.StaffService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author:石小俊
 * @Date:2023/1/3 17:07
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
@RequestMapping("/staff")
public class StaffController {

    private StaffService staffService = (StaffService) ObjectFactory.getObject("staffService");

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response){
        // 获取请求参数
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        String role = request.getParameter("role");
        String code = request.getParameter("code");
        String image = (String) request.getSession().getAttribute("code");
        try {
            Staff staff = staffService.login(loginName,password,role,code,image);
            // 此处根据方法的返回值进行页面跳转
            // 方法的返回值有三种格式
            // 1.redirect:url   重定向到指定的url地址
            // 2.url    转发到指定的url地址
            // 3.视图名    转发到指定的视图地址
                // 此处的视图仍然需要经过DispatcherServlet处理
                // 即:最终访问时需要添加指定的前缀与后缀
            // 重定向到/showMain.do
            // 根据配置,最终转发到/WEB-INF/pages/backend/main.jsp
            // 登录成功之后,将数据保存到session
            request.getSession().setAttribute("staff",staff);
            return "redirect:/showMain.do";
        } catch (RequestParameterErrorException e) {
            request.setAttribute("loginMsg",e.getMessage());
            // 转发到/showLogin.do
            // 根据配置,最终转发到/WEB-INF/pages/backend/login.jsp
            return "/showLogin.do";
        } catch (CodeErrorException e) {
            request.setAttribute("loginMsg",e.getMessage());
            // 根据配置,直接转发到/WEB-INF/pages/backend/login.jsp
            return "backend/login";
        } catch (StaffNotExistException e) {
            request.setAttribute("loginMsg",e.getMessage());
            return "backend/login";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            return "backend/login";
        }
    }


}
